<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\common\controller\Api;
use app\common\model\VipOrder;
use app\common\model\VipUser;
use think\facade\Db;
use think\Exception;
use app\common\model\Vip as VipModel;

class Vip extends Api
{

    protected $noNeedLogin = ['notify'];
    protected $noNeedRight = '*';

    public function list(){
        $list=VipModel::where(['status'=>'normal'])->order('level asc')->select()?:[];

        $this->success('成功',$list);
    }

    public function info(){
        $id=request()->param('id');

        $data=VipModel::get($id);

        if(!$data){
            $this->error('未找到对应会员等级信息');
        }
        if($data['status']!='normal'){
            $this->error('此会员等级暂不开放');
        }

        $this->success('成功',$data);
    }

    public function me(){
        $user=$this->auth->getUser();

        //会员状态:0未生效,1正常,2已过期,10已失效,20被停用
        $my_vip=VipUser::with('vip')
            ->where([['user_id','=',$user['id']],['pay_status','=',1],['expire_time','>',time()]])->find()?:[];

        if(!$my_vip){
            $exist=VipUser::where([['user_id','=',$user['id']],['pay_status','in',[1,2]],['expire_time','<',time()]])->find()?:[];
            if(!$exist){$this->error('您还未购买会员服务');}

            $exist=VipUser::where([['user_id','=',$user['id']],['pay_status','=',1],['expire_time','>',time()]])->find()?:[];
            if(!$exist){$this->error('您的会员服务已过期');}
        }

        $orders=VipOrder::alias('VO')
            ->join('fa_service_basic SB','VO.code=SB.code')
            ->where(['VO.vip_user_id'=>$my_vip['id']])->field('VO.id,VO.code,VO.status,VO.free_sn,SB.name,SB.thumb')->select()?:[];

        $records=[];
        foreach ($orders as $o){
            if(isset($records[$o['code']])){
                $records[$o['code']]['all'][]=$o;
                $records[$o['code']]['used']=[];
                $records[$o['code']]['unused']=[];
            }
            if($o['status']==1){
                $records[$o['code']]['used'][]=$o;
            }
            else{
                $records[$o['code']]['unused'][]=$o;
            }
        }
        $my_vip['records']=$records;


        $this->success('成功',$my_vip);
        //todo 登录接口更新会员状态
    }

    public function buy(){
        $user=$this->auth->getUser();
        $vip_id=request()->param('id');

        $exist=VipUser::where([['user_id','=',$user['id']],['pay_status','=',1],['expire_time','>',time()]])->find()?:[];
        if($exist){
            $this->error('您有正在生效中的会员服务，请勿重复购买');
        }

        $vip=VipModel::get($vip_id);
        if(!$vip){
            $this->error('未找到对应会员等级信息');
        }
        if($vip['status']!='normal'){
            $this->error('此会员等级暂不开放');
        }
        $vip->toArray();
        unset($vip['intro']);

        $data=[
            'user_id'               =>$user['id'],
            'vip_id'                =>$vip_id,
            'vip_info'              =>json_encode($vip),
            'vip_sn'                =>'V'.makePaySn($user['id']),
            'price'                 =>$vip['price'],
            'status'                =>0,
            'pay_status'            =>0,
            'create_time'           =>time(),
            'ward_last'             =>$vip['ward'],
            'surgery_ward_last'     =>$vip['surgery_ward'],
            'special_ward_last'     =>$vip['special_ward'],
            'escort_vip_last'       =>$vip['escort_vip'],
            'escort_last'           =>$vip['escort'],
            'escort_halfday_last'   =>$vip['escort_halfday'],
            'register_last'         =>$vip['register'],
            'inquiry_last'          =>$vip['inquiry'],
            'document_last'         =>$vip['document'],
            'medicine_last'         =>$vip['medicine'],
            'records_last'          =>$vip['records'],
            'escort_overtime_last'  =>$vip['escort_overtime'],
            'severe_illness_last'   =>$vip['severe_illness'],
            'oversea_last'          =>$vip['oversea'],
            'private_doctor_last'   =>$vip['private_doctor'],
            'famous_doctor_last'    =>$vip['famous_doctor']
        ];

        $id=VipUser::insertGetId($data);


        if(!$user['user_wx_miniapp_openid']){
            $this->error('缺少openid');
        }

        try {
            $notifyurl = $this->request->root(true) . '/Vip/notify/vip_sn/' . $data['vip_sn'];
            $returnurl = $this->request->root(true) . '/Vip/notify/vip_sn/' . $data['vip_sn'];
            $response  = Service::submitOrder(
                $data['price'],
                $data['vip_sn'],
                'wechat',
                '支付订单',
                $notifyurl,
                $returnurl,
                'miniapp',
                $user['user_wx_miniapp_openid']
            );
            adlog('支付参数',$response);
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }

        $this->success('获取支付参数成功',['response' => json_decode($response),'vip_user_id' => $id]);

    }

    public function notify(){
        adlog('会员充值回调',file_get_contents("php://input"));
        $pay     = Service::checkNotify('wechat');
        if (!$pay) {
            echo '验签失败';
            return 'failed';
        }
        $data = $pay->verify();
        adlog('支付回调',$data);
        Db::startTrans();
        try {
            $vip_sn   = request()->param('vip_sn')?:'';
            $vip_info   = VipUser::get(['vip_sn' => $vip_sn,'status' => 0,'pay_status'=>0]);
            if(!$vip_info){
                throw new Exception('未找到对应订单');
            }
            if ($vip_info) {
                $vip_info['status']=1;
                $vip_info['pay_status']=1;
                $vip_info['pay_time']=time();
                $vip_info['pay_type']='wx';
                $vip_info['platform_type']='miniapp';
                $vip_info['expire_time']=$vip_info['pay_time']+365*86400;

                $vip_info->save();

                VipOrder::buildAccess($vip_info);
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            //$this->error($e->getMessage());
            adlog('购买会员-支付错误信息',$e->getMessage());
            exit;
        }
        return 'success';
    }

}